from django.db import transaction

from gis.common import track_logging
from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException
from itpay.core.agency.const import QUICK_REPLY_COUNT_LIMIT
from itpay.core.agency.errors import ERROR_AGENCY_QUICK_REPLY_NOT_EXISTS, \
    ERROR_AGENCY_QUICK_REPLY_COUNT_LIMIT
from itpay.core.agency.models import QuickReply

_LOGGER = track_logging.getLogger(__name__)


def list_quick_reply(page_no, page_size, agency_id=None):
    query = QuickReply.objects.all()
    if agency_id:
        query = query.filter(agency_id=agency_id)
    return query.count(), [e.to_dict() for e in paginate(query.order_by('created_at'), page_no, page_size)]


def delete_quick_reply(quick_reply_id):
    QuickReply.objects.filter(id=quick_reply_id).delete()


def add_quick_reply(agency_id, title, content):
    assert agency_id
    assert title
    assert content
    quick_reply_count, _ = list_quick_reply(1, 1, agency_id)
    if quick_reply_count >= QUICK_REPLY_COUNT_LIMIT:
        raise BizException(ERROR_AGENCY_QUICK_REPLY_COUNT_LIMIT, QUICK_REPLY_COUNT_LIMIT)
    quick_reply = QuickReply(agency_id=agency_id, title=title, content=content)
    quick_reply.save()
    return quick_reply.to_dict()


def update_quick_reply(quick_reply_id, title, content):
    with transaction.atomic():
        quick_reply = _get_quick_reply(quick_reply_id, with_lock=True)
        if title:
            quick_reply.title = title
        if content:
            quick_reply.content = content
        quick_reply.save()


def _get_quick_reply(quick_reply_id, with_lock=False):
    if with_lock:
        quick_reply = QuickReply.objects.select_for_update().filter(pk=quick_reply_id).first()
    else:
        quick_reply = QuickReply.objects.filter(pk=quick_reply_id).first()
    if not quick_reply:
        raise BizException(ERROR_AGENCY_QUICK_REPLY_NOT_EXISTS, quick_reply_id)
    return quick_reply
